package educrypt.database.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import educrypt.database.Connector;

public class TextLanguageDAO extends Observable {

	/* Singleton */
	private TextLanguageDAO() {
	}

	public static TextLanguageDAO getInstance() {
		return SingletonHolder.instance;
	}

	private static class SingletonHolder {
		public static final TextLanguageDAO instance = new TextLanguageDAO();
	}

	/* END Singleton */

	public List<String> findAll() {
		String sqlFindAllLanguages = "SELECT * FROM TextLanguage";
		List<String> allLanguages = new ArrayList<String>();
		try {
			Connection conn = Connector.getConnection();
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sqlFindAllLanguages);
			while (rs.next()) {
				allLanguages.add(rs.getString("name"));
			}
			rs.close();
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return allLanguages;
	}

	public boolean exists(String language) {
		String sqlExistsTextLanguage = "SELECT COUNT(*) from TextLanguage WHERE name=?";
		boolean exists = false;
		try {
			Connection conn = Connector.getConnection();
			PreparedStatement ps = conn.prepareStatement(sqlExistsTextLanguage);
			ps.setString(1, language);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				exists = rs.getInt(1) > 0;
			}
			rs.close();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return exists;
	}

	public void create(String language) {
		if (!exists(language)) {
			String sqlCreateLanguage = "INSERT INTO TextLanguage (name) VALUES (?)";
			try {
				Connection conn = Connector.getConnection();
				PreparedStatement ps = conn.prepareStatement(sqlCreateLanguage);
				ps.setString(1, language);
				ps.executeUpdate();
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			notifyObservers();
		}
	}

	public void delete(String language) {
		String sqlDeleteLanguage = "DELETE FROM TextLanguage WHERE name=?";
		try {
			Connection conn = Connector.getConnection();
			PreparedStatement ps = conn.prepareStatement(sqlDeleteLanguage);
			ps.setString(1, language);
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		notifyObservers();
	}

	@Override
	public void notifyObservers() {
		this.setChanged();
		List<String> textLanguages = this.findAll();
		this.notifyObservers(textLanguages);
	}
}
